/**
 * Created by QIAODI on 8/24/2016.
 */
const mongoose = require("mongoose");
const request = require("request");
const async = require('async');
var Merchant = mongoose.model("merchant");

exports.queryMerchant = function (req, res) {
    var mid = req.params.mid;
    Merchant.find({_id: mid})
        .exec(function (err, merchant) {
            if (!err) {
                res.json(merchant);
            }
            else {
                res.json({error: "queryMerchant"});
            }
        });
}


exports.queryAllMerchants = function (req, res) {

    var mids = [];
    var merchantDetails = {};
    Merchant.find({})
        .exec(function (err, merchants) {
            if (!err) {
                for (var i = 0; i < merchants.length; i++) {
                    mids.push(merchants[i]._id);
                }

                async.each(merchants, function (merchant, callback) {
                    merchantDetails[merchant._id] = merchant;
                    callback();
                }, function (err) {
                    console.log(merchantDetails);
                    res.json(merchantDetails);
                });
            }
        });
}


exports.queryMerchants = function (req, res) {
    var mids = JSON.parse(req.body.mids);
    var merchantDetails = {};
    async.each(mids, function (mid, callback) {
        Merchant.find({_id: mid})
            .exec(function (err, merchants) {
                if (!err) {
                    merchantDetails[mid] = merchants;
                    callback();
                }
                else {
                    res.json({error: "queryMerchants"});
                }
            });
    }, function (err) {
        console.log(merchantDetails);
        res.json(merchantDetails);
    });
}
